/**
 * 
 */
var isAppletLoaded = false;
var isFriendsDataLoaded = false;
var isMessageDataLoaded = false;
var isPostDataLoaded = false;
var isFriendCommentDataLoaded = false;
var isMyNoteCommentDataLoaded = false;
var isMyLinkCommentDataLoaded = false;
var isMyStatusCommentDataLoaded = false;
var isFriendLikeDataLoaded = false;
var isMyLikeDataLoaded = false;

var threshold = 0;
var maxScore = 100;
var maxDistance = 250;

$(document).ready(function(){
	
    [##_AJAX_FUNCTION_##]
	
    $('#refresh-image').hide();
    $('#threshold').val(threshold);
    $('#slider').slider({
        slide: function(event,ui){
            threshold = ui.value;
            $('#threshold').val(threshold);
            drawGraph();
        }
    });

	var dWidth = 320;
	var dHeight = 400;
	
	shimIFrame();
	$('#friend-container').dialog({ 
	    autoOpen: false,
	    width: 300, 
	    height: 270,
	    position: [300, 300],
	    open: function(event, ui){
			
	        $('#shimmer')
	            .css('left', $('.ui-dialog').css('left'))
	            .css('top' , $('.ui-dialog').css('top'))
	            .width($('.ui-dialog').width()+8)
	            .height($('.ui-dialog').height()+8)
	            .show();
	    },
	    drag: function(event, ui){
	        $('#shimmer')
	            .css('left', ui.position.left)
	            .css('top', ui.position.top)
	    },
	    resize: function(event, ui){
	        $('#shimmer')
	            .css('left', ui.position.left)
	            .css('top' , ui.position.top)
	            .width($('.ui-dialog').width()+8)
	            .height($('.ui-dialog').height()+8);
	    },
	    close: function(event, ui){
	        $('#shimmer').hide();
	    }
	});   
    
    //Button Event Handlers
    $('#refresh-image').click(drawGraph);
    $('#remove_zero_score').change(drawGraph);
    $('#show_friend_table').click(function(){
        $('#friend-container').dialog("open");
    });
	$('#friends_of_friends').click(function(){
		getFriendsOfFriendsAJAX();
	});

});

function drawGraph(){

    if(isAppletLoaded && isFriendsDataLoaded){

	    //sort uing tablesorter http://tablesorter.com
	    $("table.rankTable").tablesorter({ 
	        // sort on the 8th column, order dsc 
	        sortList: [[7,1]] 
	    });
		
		$("table.rankTable tbody tr").each(function(index, row){
			var cols = $(row).children();
			cols.eq(0).text(index+1);
		});

        var obj = document.getElementById('friendsNet');
		
		//show graph
		obj.setAttribute("style", "visibility:visible;");
        
        if (obj != null) {
            obj.setMaxDistance(maxDistance);
            obj.clearGraph();
    
            var maxValue = 100;
            var friends = $('table.rankTable');
            $('tr', friends).each(function(index){
                if (index != 0) {
                    var cols = $(this).children();
                    var score = 0;
					
					//add message point if checked
					if($('#chk_message').attr('checked') != "undefined" && $('#chk_message').attr('checked') == 'checked'){
						score =+ (cols.eq(3).text() - 0);
					}
					//add post points if checked
					if($('#chk_post').attr('checked') != "undefined" && $('#chk_post').attr('checked') == 'checked'){
                        score =+ (cols.eq(4).text() - 0);
                    }
					//add comment if checked
					if($('#chk_comment').attr('checked') != "undefined" && $('#chk_comment').attr('checked') == 'checked'){
                        score =+ (cols.eq(5).text() - 0);
                    }
					//add like if checked
					if($('#chk_like').attr('checked') != "undefined" && $('#chk_like').attr('checked') == 'checked'){
                        score =+ (cols.eq(6).text() - 0);
                    }
					
                    if (index == 1 && (cols.eq(8).text() != 0)) {
                        maxValue = cols.eq(8).text();
						//give slider max value
                        $('#slider').slider("option", "max", maxValue);
                    }
                    fId = $(cols.eq(1)).attr('id');
                    name = cols.eq(1).text();
    
                    if(score >= threshold){
                        obj.addFriend(fId, name, getDistance(score, maxValue));
                    }
    
                }
            });
        }
    }
}

function getFriendsAJAX(){
	
	$('.subtitle').show();
    $('table.rankTable tbody').empty();
	var applet = document.getElementById('friendsNet');
	applet.setAttribute("style", "visibility:hidden");
	$('#loading-box').html("Loading friends data").show();
	
	if ($.data(document.body, 'friends') != null) {
		
		//hide loading image
        $('#loading-box').hide();

        //Build Friend Table
        buildFriendTable($.data(document.body, 'friends'));
    
	   //onLoad Event Handler		
        onFriendsDataLoaded();
		
	} else {
			
		$.getJSON(app_dir+'/ajax/getFriendsAJAX.php?[##_QUERY_STRING_##]', null, function(data){

            //hide loading image
			$('#loading-box').hide();

			//check if there is an error
			if(data.error != null){
				if(confirm(data.error + "\nPress OK to try again")){
                    getFriendsAJAX();					
				}
            }else{
			
				//store data 
				$.data(document.body, 'friends', data);
				
				//Build Friend Table
				buildFriendTable(data);

                //onLoad Event Handler				
				onFriendsDataLoaded();
				
            }				
		});
	}        
}

function getFriendRankAJAX(type){

    $('#message').html("Processing Data").show();
	
    if ($.data(document.body, type) != null) {
        //extract data
        data = $.data(document.body, type);
        
        //Build Friend Table
        addToFriendTable(data);
        
        //Call onLoad Event Handler
        onDataLoaded(type);
    }
    else {
		mode = getModeByType(type);
        $.getJSON(app_dir+'/ajax/getFriendsDataAJAX.php?mode='+mode+'&[##_QUERY_STRING_##]', null, function(data){
        
            //check if there is an error
            if (data.error != null) {
                if (confirm(data.error + "\nPress OK to try again")) {
                    getFriendRankAJAX(type);
                }
            }
            else {
            
                //store data 
                $.data(document.body, type, data);
                
                //Build Friend Table
                addToFriendTable(type, data);

                //onLoad Event Handler              
                onDataLoaded(type);
				
				$.noticeAdd({
				    text:type + " data done.",
					stay:false
				});
                
            }
        });
    }
}

function getFriendsOfFriendsAJAX(){

    if ($.data(document.body, 'friendsOfFriends') != null) {
        
        //hide loading image
        $('#loading-box').hide();
        
        addRelations($.data(document.body, 'friendsOfFriends'));
                        
    } else {
            
        $.getJSON(app_dir+'/ajax/getFriendsOfFriendsAJAX.php?[##_QUERY_STRING_##]', null, function(data){

            //hide loading image
            $('#loading-box').hide();

            //check if there is an error
            if(data.error != null){
                alert(data.error);
            }else{
            
                //store data 
                $.data(document.body, 'friendsOfFriends', data);

                addRelations(data);
                
            }               
        });
    }
}

function addRelations(data){
    var applet = document.getElementById('friendsNet');
	applet.initFriendsOfFriends();
    $(data).each(function(index, item){
        //Spring makeSpring( Particle a, Particle b, float strength, float damping, float restLength )
        applet.addRelation(item.id1, item.id2, 0.01, 0.01, 100);
    });
}

function buildFriendTable(data){
    var tbody = $('table.rankTable tbody');
    $(data).each(function(item, value){
		
        tbody.append("<tr id='row_"+ value.fId +"'>" + 
                          "<td>"+ eval(item + 1) +"</td>" + 
                          "<td id='"+ value.fId +"'><a target='_blank' href='[##_MY_LINK_URL_##]and=" + value.fId + "'>" + value.name +"</td>" +
						  "<td class='strengthOfTie'>0</td>" + 
						  "<td class='messagePoint'>0</td>" +
						  "<td class='postPoint'>0</td>" +
						  "<td class='commentPoint'>0</td>" +
                          "<td class='likePoint'>0</td>" +
						  "<td class='totalPoint'>0</td>" +
                    "</tr>");
    });
}

function addToFriendTable(type, data){

    if(type == 'message'){
        nth = 4;
    }else if(type == 'post'){
        nth = 5;
    }else if(type == 'friendComment'){
        nth = 6;
    }else if(type == 'friendLike'){
        nth = 7;
    }else if(type == 'myNoteComment'){
        nth = 6;
    }else if(type == 'myLinkComment'){
        nth = 6;
    }else if(type == 'myStatusComment'){
        nth = 6;
    }else if(type == 'myLike'){
        nth = 7;
    }
	
    var tbody = $('table.rankTable tbody');
	$(data).each(function(index, item){
		var obj = $('#row_'+item.fId + ' td:nth-child('+ nth +')');
		var score = (obj.text()-0) + (item.score-0);
		//var score = ($('#'+item.fId).next().text()-0) + (item.score-0);
		obj.text(score);
		
		var objTotal = $('#row_'+item.fId + ' td:nth-child(8)');
		objTotal.text((objTotal.text()-0) + (item.score-0));
	});
}

function onAppletLoaded(){
    isAppletLoaded = true;
    drawGraph();
}

function onFriendsDataLoaded(){
    isFriendsDataLoaded = true;
    drawGraph();	
	getFriendRankAJAX('message');
	getFriendRankAJAX('post');
	getFriendRankAJAX('friendComment');
	getFriendRankAJAX('friendLike');
	getFriendRankAJAX('myNoteComment');
	getFriendRankAJAX('myStatusComment');
	getFriendRankAJAX('myLinkComment');
	getFriendRankAJAX('myLike');
}

function onDataLoaded(type){
	if(type == 'message'){
		isMessageDataLoaded = true;
		$('#span_message').show();
	}else if(type == 'post'){
		isPostDataLoaded = true;
		$('#span_post').show();
	}else if(type == 'friendComment'){
		isFriendCommentDataLoaded = true;
	}else if(type == 'friendLike'){
		isFriendLikeDataLoaded = true;
	}else if(type == 'myNoteComment'){
		isMyNoteCommentDataLoaded = true;
    }else if(type == 'myLinkComment'){
        isMyLinkCommentDataLoaded = true;
    }else if(type == 'myStatusComment'){
        isMyStatusCommentDataLoaded = true;
	}else if(type == 'myLike'){
		isMyLikeDataLoaded = true;
		$('#span_like').show();
	}

	if(isMessageDataLoaded && isPostDataLoaded && isFriendCommentDataLoaded && isFriendLikeDataLoaded 
	   && isMyNoteCommentDataLoaded && isMyLinkCommentDataLoaded && isMyStatusCommentDataLoaded && isMyLikeDataLoaded){
		//show refresh button
        $('#refresh-image').show();
		
        //hide loading image
        $('#message').empty().hide();
		
		drawGraph();
	}
}
function linkToFriendshipPage(id){
	var url = app_dir+"/friendship.php?[##_QUERY_STRING_##]&fId=" + id;
	if (confirm("Do you want to go to the friendship page?")) {
	   window.location.href = url;
    }
}

function getModeByType(type){
	var mode = 0;

	if(type == 'message'){
		mode = 1;
	}else if(type == 'post'){
		mode = 2;
	}else if(type == 'friendComment'){
		mode = 4;
	}else if(type == 'friendLike'){
		mode = 8;
	}else if(type == 'myNoteComment'){
        mode = 16;
    }else if(type == 'myLinkComment'){
        mode = 32;
    }else if(type == 'myStatusComment'){
        mode = 64;
	}else if(type == 'myLike'){
		mode = 896;
	}
	return mode;
}
